package cn.com.bluemoon.daps.model.core.file.excel.converter;

import com.alibaba.excel.converters.booleanconverter.BooleanStringConverter;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.commons.collections4.map.CaseInsensitiveMap;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义string转为boolean
 *
 * @author Jarod.Kong
 * @date 2021/2/7 15:54
 */
public class CustomBooleanStringConverter extends BooleanStringConverter {
    public static final CaseInsensitiveMap<String, Boolean> STR_TO_BOOL = new CaseInsensitiveMap<String, Boolean>(8);

    public static final Map<Boolean, String> BOOL_TO_STR = new HashMap<Boolean, String>(4);

    static {
        {
            STR_TO_BOOL.put("yes", Boolean.TRUE);
            STR_TO_BOOL.put("no", Boolean.FALSE);
            STR_TO_BOOL.put("", Boolean.FALSE);
            STR_TO_BOOL.put(null, Boolean.FALSE);
        }
        {
            BOOL_TO_STR.put(Boolean.FALSE, "NO");
            BOOL_TO_STR.put(Boolean.TRUE, "YES");
        }
    }

    @Override
    public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        String strBoolean = cellData.getStringValue();
        Boolean bool = Boolean.FALSE;
        if (STR_TO_BOOL.get(strBoolean) != null) {
            bool = STR_TO_BOOL.get(strBoolean);
        }
        return bool;
    }

    @Override
    public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        String boolStr;
        try {
            boolStr = BOOL_TO_STR.get(value);
        } catch (Exception e) {
            boolStr = BOOL_TO_STR.get(Boolean.FALSE);
        }
        return new CellData(boolStr);
    }
}
